package sg.edu.ntu.metaweb.storage.data;


import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

public class Webpage implements Serializable {

	private int webpageID;
	private URL url;
	
	private HashMap<User, Rating> ratings;
	private HashSet<Tag> tags;
	private HashSet<Link> links;
	private ArrayList<Comment> comments;
	
	public Webpage(String url) {
		this.webpageID = url.hashCode();
		this.ratings = new HashMap<User, Rating>();
		this.tags = new HashSet<Tag>();
		this.links = new HashSet<Link>();
		this.comments = new ArrayList<Comment>();
		
		try {
			this.url = new URL(url);
		}
		catch(MalformedURLException exc) {
			exc.printStackTrace();
		}
	}

	
	public int getWebpageID() {
		return webpageID;
	}


	public URL getUrl() {
		return url;
	}


	public HashMap<User, Rating> getRatings() {
		return ratings;
	}


	public HashSet<Tag> getTags() {
		return tags;
	}


	public HashSet<Link> getLinks() {
		return links;
	}


	public ArrayList<Comment> getComments() {
		return comments;
	}


	public void addRating(User user, byte value) {
		Rating newRating = new Rating(value);
		this.ratings.put(user, newRating);
	}
	
	
	public boolean addTag(Tag tag) {
		return this.tags.add(tag);
	}
	
	public boolean addTag(User creator, String text) {
		Tag newTag = new Tag(creator, text);
		return this.tags.add(newTag);
	}
	
	
	public boolean addLink(Link link) {
		return this.links.add(link);
	}
	
	public boolean addLink(User creator, String url, byte type) {
		Link newLink = new Link(creator, url, type);
		return this.links.add(newLink);
	}
	
	
	public void addComment(Comment comment) {
		this.comments.add(comment);
	}
	
	public void addComment(User commentator, String text) {
		Comment newComment = new Comment(commentator, text);
		this.comments.add(newComment);
	}
	

	public double getAveragePageRating() {
		double rating = 0.0;
		
		Iterator<Rating> ratingIterator = ratings.values().iterator();
		while (ratingIterator.hasNext()) {
			rating += ratingIterator.next().getValue();
		}
		
		return rating / ratings.size();
	}
	
	
	public String toXMLString() {
		String returnString = "";
		
		returnString += "<webpage>\n";
		
		// Create average page rating
		//returnString += "<avgrating>\n" + this.getAveragePageRating() + "\n</avgrating>\n";
		
		// For testing
		returnString += "<avgrating>\n4.5\n</avgrating>\n";
		
		returnString += "</webpage>\n";
		
		return returnString;
	}
	
}
